<template>
  <div class="container":style="{ backgroundImage: `url(${background})` , backgroundSize: 'cover', backgroundRepeat: 'no-repeat',backgroundPosition: 'center'}">
    <header class="header">
      <h1>杂草检测系统实时检测驾驶舱</h1>
    </header>
    <main class="main">
      <section class="left-content">
        <!-- 左侧内容 -->
        <section class="left-content-up" ref="leftContentUp">
          <!-- 左侧内容 -->
        </section>
        <section class="left-content-down" ref="leftContentDown">
          <!-- 左侧内容 -->
        </section>
      </section>
      <section class="middle-content">
        <!-- 中部内容 -->
        <img src="http://127.0.0.1:5000/video_feed" alt="Video Stream" id="video-stream">
      </section>
      <section class="right-content">
        <!-- 右侧内容 -->
        <section class="right-content-up" ref="rightContentUp">
          <!-- 左侧内容 -->
        </section>
        <section class="right-content-down" ref="rightContentDown">
          <!-- 左侧内容 -->
        </section>
      </section>
    </main>
    <footer class="footer">
      <!-- 底部内容 -->
    </footer>
  </div>
</template>

<script>
import echarts from 'echarts'
import Background from '@/assets/detect/backgroung-shishi.png'
//import io from 'socket.io-client';
// require('echarts/theme/macarons') // echarts theme
export default {
  name: 'IndexPage',
  data() {
    return {
      background: Background,
      fps_y_data: Array.from({ length: 60 }, () => Math.floor(Math.random() * (130 - 70 + 1)) + 70),
      rightChartData: [
        { name: '早熟禾', value: 1, itemStyle: { color: '#FF5733' } },
        { name: '藜（灰菜）', value: 2, itemStyle: { color: '#29a13d' } },
        { name: '刺儿菜', value: 3, itemStyle: { color: '#5e75e5' } },
        { name: '玉米', value: 1, itemStyle: { color: '#c5ce42' } },
        { name: '莎草', value: 3, itemStyle: { color: '#7c1275' } },
        { name: '马齿苋', value: 0, itemStyle: { color: '#0e8883' } }
      ]
    };
  },
  mounted() {
    this.initChartUp();
    this.initRightChartUp();
    this.initChartDown();
    this.initRightChartDown();
    this.pollForDetectedObjects();
    this.pollForDetectedFps();
  },
  methods: {
    initChartUp() {
      const chartDom = this.$refs.leftContentUp;
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '不同杂草的锚框数量',
          left: 'center',
          textStyle: {
            color: '#000000', // 标题颜色
            fontWeight: 'bold' // 标题加粗
          }
        },
        tooltip: {},
        legend: {
          data: ['锚框数'],
          right: '10%', // 将图例放置在右上角
          top: '10%',
          textStyle: {
            color: '#000000', // 图例颜色
            fontWeight: 'bold' // 图例加粗
          }
        },
        xAxis: {
          data: ["早熟禾", "藜（灰菜）", "刺儿菜", "玉米", "莎草", "马齿苋"],
          axisLabel: {
            interval: 0, // 强制显示所有标签
            rotate: 45, // 旋转标签以防止重叠
            margin: 10, // 标签与轴线的距离
            color: '#000000', // 横坐标字体颜色
            fontWeight: 'bold' // 横坐标字体加粗
          },
          axisLine: {
            lineStyle: {
              color: '#FFFFFF' // 横坐标轴线颜色
            }
          },
          axisTick: {
            lineStyle: {
              color: '#FFFFFF' // 横坐标刻度线颜色
            }
          }
        },
        yAxis: {
          axisLabel: {
            formatter: function (value) {
              return Math.round(value);
            },
            color: '#000000', // 纵坐标字体颜色
            fontWeight: 'bold' // 纵坐标字体加粗
          },
          axisLine: {
            lineStyle: {
              color: '#FFFFFF' // 纵坐标轴线颜色
            }
          },
          axisTick: {
            lineStyle: {
              color: '#FFFFFF' // 纵坐标刻度线颜色
            }
          },
          splitLine: {
            lineStyle: {
              color: '#FFFFFF' // 纵坐标参考线颜色
            }
          }
        },
        series: [{
          name: '锚框数',
          type: 'bar',
          data: [1, 2, 3, 1, 3, 0],
          itemStyle: {
            color: '#FF5733' // 柱状图颜色
          }
        }]
      };
      myChart.setOption(option);
    },
    initRightChartUp() {
      const chartDom = this.$refs.rightContentUp;
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '目标比例',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: '10%', // 将图例放置在右上角
          top: '10%',
          data: ["早熟禾", "藜（灰菜）", "刺儿菜", "玉米", "莎草", "马齿苋"]
        },
        series: [
          {
            name: '比例',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: [
              { name: '早熟禾', value: 1 },
              { name: '藜（灰菜）', value: 2 },
              { name: '刺儿菜', value: 3 },
              { name: '玉米', value: 1 },
              { name: '莎草', value: 3 },
              { name: '马齿苋', value: 0 }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    initChartDown() {
      const chartDom = this.$refs.leftContentDown;
      const myChart = echarts.init(chartDom);
      const fps_x_data = Array.from({ length: 60 }, (_, i) => `前${60 - i}帧`);
      const option = {
        title: {
          text: '检测FPS-实时',
          left: 'center'
        },
        tooltip: {},
        legend: {
          data: ['FPS'],
          right: '10%', // 将图例放置在右上角
          top: '10%'
        },
        xAxis: {
          data: fps_x_data,
          axisLabel: {
            color: '#000000', // 横坐标字体颜色

          },

        },
        yAxis: {
          axisLabel: {
            color: '#000000', // 横坐标字体颜色

          },
        },
        series: [{
          name: 'fps',
          type: 'line',
          itemStyle: {
            color: '#f5364b' // 柱状图颜色
          },
          data: this.fps_y_data,
        }]
      };
      myChart.setOption(option);
      this.myChart = myChart; // 保存图表实例以便后续更新
    },
    initRightChartDown() {
      const chartDom = this.$refs.rightContentDown;
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '实时检测的目标数量',
          left: 'center'
        },
        tooltip: {},
        legend: {
          data: ['数量'],
          right: '10%', // 将图例放置在右上角
          top: '10%'
        },
        xAxis: {
          data: ["早熟禾", "藜（灰菜）", "刺儿菜", "玉米", "莎草", "马齿苋"],
          axisLabel: {
            interval: 0, // 强制显示所有标签
            rotate: 45, // 旋转标签以防止重叠
            margin: 10, // 标签与轴线的距离
            color: '#333131', // 横坐标字体颜色
            fontWeight: 'bold' // 横坐标字体加粗
          }
        },
        yAxis: {
          axisLabel: {
            formatter: function (value) {
              return Math.round(value);
            },
            color: '#000000', // 横坐标字体颜色
            fontWeight: 'bold' // 横坐标字体加粗
          }
        },
        series: [{
          name: '',
          type: 'bar',
          data: this.rightChartData,
          label: {
            show: true,
            position: 'top',
            formatter: '{c}'
          }
        }]
      };
      myChart.setOption(option);
      this.rightChart = myChart; // 保存图表实例以便后续更新
    },
    pollForDetectedObjects() {
      setInterval(() => {
        fetch('http://127.0.0.1:5000/get_detected_objects')
          .then(response => response.json())
          .then(data => {
            console.log('Received detected objects:', data);
            // 提取并映射数据
            const newData = [
              { name: '早熟禾', value: data.bluegrass || 0, itemStyle: { color: '#FF5733' } },
              { name: '藜（灰菜）', value: data['chenopodium album'] || 0, itemStyle: { color: '#29a13d' } },
              { name: '刺儿菜', value: data['cirsium setosum'] || 0, itemStyle: { color: '#5e75e5' } },
              { name: '玉米', value: data.corn || 0, itemStyle: { color: '#c5ce42' } },
              { name: '莎草', value: data.sedge || 0, itemStyle: { color: '#7c1275' } },
              { name: '马齿苋', value: data['portulaca oleracea'] || 0, itemStyle: { color: '#0e8883' } }
            ];
            // 更新 rightChartData
            this.rightChartData = newData;
            // 更新图表数据
            this.rightChart.setOption({
              series: [{
                data: this.rightChartData
              }]
            });
          })
          .catch(error => console.error('Error fetching detected objects:', error));
      }, 1000); // 每1秒请求一次
    },
    pollForDetectedFps() {
      setInterval(() => {
        fetch('http://127.0.0.1:5000/get_detected_FPS')
          .then(response => response.json())
          .then(data => {
            console.log('Received detected FPS:', data);
            // 假设 data 是一个包含 FPS 值的对象，例如 { fps: 120 }
            const newFpsValue = data;

            // 更新 fps_y_data 数组
            for (let i = 0; i < this.fps_y_data.length - 1; i++) {
              this.fps_y_data[i] = this.fps_y_data[i + 1];
            }
            this.fps_y_data[this.fps_y_data.length - 1] = newFpsValue;

            // 更新图表数据
            this.myChart.setOption({
              series: [{
                data: this.fps_y_data
              }]
            });
          })
          .catch(error => console.error('Error fetching detected FPS:', error));
      }, 1000); // 每1秒请求一次
    }
  }
}
</script>

<style scoped>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  margin: 0;
  padding: 0;
}

.header {

  height: 17%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin: 0;
  padding: 0;
}

.main {
  display: flex;
  height: 65%;
  margin: 0;
  padding: 0;
}

.middle-content {

  width: 43%;
  margin: 0;
  padding: 0;
}

.middle-content img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图像比例并裁剪以填充容器 */
}

.left-content {

  width: 25%;
  margin-left: 60px;
  padding: 0;
}

.left-content-down {
  flex: 1;

  margin-left: 12px;
  height: 50%;
  box-sizing: border-box;
}

.left-content-up {
  flex: 1;

  margin: 0;
  height: 50%;
  box-sizing: border-box;
}

.right-content {

  width: 27%;
  margin-left: 0px;
  padding: 0;
}

.right-content-down {
  flex: 1;
  margin: 0;
  height: 50%;
  box-sizing: border-box;
}

.right-content-up {
  flex: 1;

  margin: 0;
  height: 50%;
  box-sizing: border-box;
}

.footer {

  height: 10%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin: 0;
  padding: 0;
}
</style>
